<template>
  <div class="handle-workbench-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>待处理报警清单</span>
          <el-button type="primary" size="small" @click="refreshAlarms">刷新</el-button>
        </div>
      </template>
      
      <el-table 
        :data="pendingAlarms" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="alarmCode" label="报警编码" width="150" />
        <el-table-column prop="sourceName" label="报警来源" width="120" />
        <el-table-column prop="alarmType" label="报警类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlarmTypeTag(row.alarmType)">
              {{ getAlarmTypeName(row.alarmType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="alarmLevel" label="报警级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getAlarmLevelTag(row.alarmLevel)">
              {{ getAlarmLevelName(row.alarmLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="alarmContent" label="报警内容" show-overflow-tooltip />
        <el-table-column prop="triggerTime" label="触发时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.triggerTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleProcess(row)">处理</el-button>
            <el-button type="info" size="small" @click="handleDetail(row)">详情</el-button>
            <el-button type="success" size="small" @click="handleClaim(row)">认领</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 处理表单弹窗 -->
    <el-dialog v-model="processDialogVisible" title="处理报警" width="60%">
      <el-form :model="processForm" :rules="processRules" ref="processFormRef" label-width="120px">
        <el-form-item label="报警ID">
          <el-input v-model="processForm.alarmId" disabled />
        </el-form-item>
        <el-form-item label="处理人" prop="handlerId">
          <el-select v-model="processForm.handlerId" placeholder="请选择处理人" style="width: 100%">
            <el-option label="当前用户" value="current_user" />
            <!-- 这里应该从用户列表获取 -->
          </el-select>
        </el-form-item>
        <el-form-item label="处理时间" prop="handleTime">
          <el-date-picker 
            v-model="processForm.handleTime" 
            type="datetime" 
            placeholder="选择处理时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="问题原因分析" prop="reasonAnalysis">
          <el-input 
            v-model="processForm.reasonAnalysis" 
            type="textarea" 
            :rows="4"
            placeholder="请输入问题原因分析" />
        </el-form-item>
        <el-form-item label="处理措施" prop="handleMeasure">
          <el-input 
            v-model="processForm.handleMeasure" 
            type="textarea" 
            :rows="4"
            placeholder="请输入处理措施" />
        </el-form-item>
        <el-form-item label="处理结果" prop="handleResult">
          <el-select v-model="processForm.handleResult" placeholder="请选择处理结果" style="width: 100%">
            <el-option label="问题已解决" :value="1" />
            <el-option label="问题暂缓解" :value="2" />
            <el-option label="无法处理需升级" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload
            :action="uploadUrl"
            :on-success="handleUploadSuccess"
            :file-list="fileList">
            <el-button type="primary">上传附件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持JPG/PNG/PDF格式，最大10MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcess">提交</el-button>
        <el-button type="info" @click="saveDraft">保存草稿</el-button>
      </template>
    </el-dialog>
    
    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="报警详情" width="60%">
      <AlarmDetail :alarm-id="currentAlarmId" v-if="detailDialogVisible" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getPendingAlarms, handleAlarm } from '@/api/prod_operate/alarm_management'
import AlarmDetail from './AlarmDetail.vue'

const loading = ref(false)
const pendingAlarms = ref([])
const selectedAlarms = ref([])
const processDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentAlarmId = ref(null)
const processFormRef = ref(null)

const processForm = ref({
  alarmId: null,
  handlerId: 'current_user',
  handleTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
  reasonAnalysis: '',
  handleMeasure: '',
  handleResult: null,
  attachmentUrl: ''
})

const processRules = {
  handlerId: [{ required: true, message: '请选择处理人', trigger: 'change' }],
  handleTime: [{ required: true, message: '请选择处理时间', trigger: 'change' }],
  reasonAnalysis: [{ required: true, message: '请输入问题原因分析', trigger: 'blur' }],
  handleMeasure: [{ required: true, message: '请输入处理措施', trigger: 'blur' }],
  handleResult: [{ required: true, message: '请选择处理结果', trigger: 'change' }]
}

const fileList = ref([])
const uploadUrl = '/operation/api/upload' // 实际上传地址

// 获取待处理报警列表
const fetchPendingAlarms = async () => {
  loading.value = true
  try {
    const res = await getPendingAlarms()
    if (res.code === 200) {
      pendingAlarms.value = res.data || []
    } else {
      ElMessage.error(res.msg || '查询失败')
    }
  } catch (error) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 刷新
const refreshAlarms = () => {
  fetchPendingAlarms()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedAlarms.value = selection
}

// 处理报警
const handleProcess = (row) => {
  processForm.value.alarmId = row.id
  processForm.value.handlerId = 'current_user'
  processForm.value.handleTime = new Date().toISOString().slice(0, 19).replace('T', ' ')
  processForm.value.reasonAnalysis = ''
  processForm.value.handleMeasure = ''
  processForm.value.handleResult = null
  processForm.value.attachmentUrl = ''
  fileList.value = []
  processDialogVisible.value = true
}

// 查看详情
const handleDetail = (row) => {
  currentAlarmId.value = row.id
  detailDialogVisible.value = true
}

// 认领报警
const handleClaim = (row) => {
  ElMessage.success('认领成功')
  refreshAlarms()
}

// 上传成功
const handleUploadSuccess = (response) => {
  processForm.value.attachmentUrl = response.url
  ElMessage.success('上传成功')
}

// 提交处理
const submitProcess = async () => {
  if (!processFormRef.value) return
  
  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await handleAlarm(processForm.value)
        if (res.code === 200) {
          ElMessage.success('处理成功')
          processDialogVisible.value = false
          refreshAlarms()
        } else {
          ElMessage.error(res.msg || '处理失败')
        }
      } catch (error) {
        ElMessage.error('处理失败：' + error.message)
      }
    }
  })
}

// 保存草稿
const saveDraft = () => {
  ElMessage.info('草稿保存功能开发中')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取报警类型标签
const getAlarmTypeTag = (type) => {
  const map = { 1: 'danger', 2: 'warning', 3: 'info' }
  return map[type] || 'info'
}

// 获取报警类型名称
const getAlarmTypeName = (type) => {
  const map = { 1: '设备故障', 2: '参数超标', 3: '通讯中断' }
  return map[type] || '未知'
}

// 获取报警级别标签
const getAlarmLevelTag = (level) => {
  const map = { 1: 'danger', 2: 'warning', 3: 'info' }
  return map[level] || 'info'
}

// 获取报警级别名称
const getAlarmLevelName = (level) => {
  const map = { 1: '紧急', 2: '重要', 3: '一般' }
  return map[level] || '未知'
}

onMounted(() => {
  fetchPendingAlarms()
})
</script>

<style scoped>
.handle-workbench-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

